package org.lmind.rom.util;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.commons.io.input.SwappedDataInputStream;

public class LocalFileHeader {
	
	public static final int SIGNAL = 0x04034b50;
	
	private int version;
	
	private int flag;
	
	private int compressionMethod;
	
	private Date lastModify;
	
	private int crc32;
	
	private long compressedSize;
	
	private long uncompressedSize;
	
	private String fileName;
	
	private byte[] extraField;

	public int getVersion() {
		return version;
	}

	public int getFlag() {
		return flag;
	}

	public int getCompressionMethod() {
		return compressionMethod;
	}

	public Date getLastModify() {
		return lastModify;
	}

	public int getCrc32() {
		return crc32;
	}

	public long getCompressedSize() {
		return compressedSize;
	}

	public long getUncompressedSize() {
		return uncompressedSize;
	}

	public String getFileName() {
		return fileName;
	}

	public byte[] getExtraField() {
		return extraField;
	}

	public static LocalFileHeader read(InputStream in) throws EOFException, IOException {
		LocalFileHeader header = new LocalFileHeader();
		SwappedDataInputStream input = new SwappedDataInputStream(in);
		
		int signal = input.readInt();
		if (signal != SIGNAL)
			throw new IOException();
		header.version = input.readUnsignedShort();
		header.flag = input.readUnsignedShort();
		header.compressionMethod = input.readUnsignedShort();
		int fileTime = input.readUnsignedShort();
		int fileDate = input.readUnsignedShort();
		header.crc32 = input.readInt();
		header.compressedSize = input.readInt();
		header.uncompressedSize = input.readInt();
		int fileNameLength = input.readUnsignedShort();
		int extraFieldLength = input.readUnsignedShort();
		
		byte[] fileNameData = new byte[fileNameLength];
		input.readFully(fileNameData);
		header.fileName = new String(fileNameData, "ascii");
		header.extraField = new byte[extraFieldLength];
		input.readFully(header.extraField);
		
		return header;
	}
}
